import { getRouteQuery } from '@/utils'
import { uuid } from '@/utils/random'

export default function useBusinessConfig() {
  const routeQuery = getRouteQuery()

  /**
   * @description 检测是否使用在线视频
   * @param routeQuery {Object} 路由参数
   * @returns {boolean}
   */
  const isOnline = (routeQuery: LooseObject = getRouteQuery()) => {
    return Reflect.has(routeQuery, 'online')
  }

  /**
   * @description 检测是否为测试模式
   * @param routeQuery {Object} 路由参数
   * @returns {boolean}
   */
  const whiteListDebug = ['test-aiforce.xmov.ai', 'localhost']
  const isDebug = (routeQuery: LooseObject = getRouteQuery()) => {
    const host = `${location.hostname}`
    return Reflect.has(routeQuery, 'debug') || whiteListDebug.includes(host) || host.startsWith('192.168.')
  }

  /**
   * @description 检测open时是否刷新缓存
   * @param routeQuery {Object} 路由参数
   * @returns {boolean}
   */
  const isRefreshIntention = (routeQuery: LooseObject = getRouteQuery()) => {
    return Reflect.has(routeQuery, 'refresh') || undefined
  }

  /**
   * @description 检测chat时是否使用问答库缓存
   * @param routeQuery {Object} 路由参数
   * @returns {boolean}
   */
  const isRefreshFaqCache = (routeQuery: LooseObject = getRouteQuery()) => {
    return Reflect.has(routeQuery, 'refresh_faq_cache') || undefined
  }

  /**
   * @description tag
   * @param routeQuery {Object} 路由参数
   * @returns {string}
   */
  const matchRouteTag = (routeQuery: LooseObject = getRouteQuery()) => {
    const tag = routeQuery.tag || ''
    return isDebug() ? tag : ''
  }

  /**
   * @description 获取url参数中的user_id - 未获取时自动生成
   * @remarks `user_id` | `userId` 两个字段名均可, `user_id`优先级更高
   * @param routeQuery {Object} 路由参数
   * @returns {string}
   */
  const matchRouteUserId = (routeQuery: LooseObject = getRouteQuery()) => {
    const storeUserIdKey = 'user_id'
    let userId = routeQuery.user_id || routeQuery.userId || localStorage.getItem(storeUserIdKey)
    if (!userId) {
      userId = uuid()
    }
    localStorage.setItem(storeUserIdKey, userId)
    return userId
  }

  /**
   * @description app_id - 未获取时使用内部测试数字人
   * @remarks `app_id` | `appId` 两个字段名均可, `app_id`优先级更高
   * @param routeQuery {Object} 路由参数
   * @returns {string}
   */
  const matchRouteAppId = (routeQuery: LooseObject = getRouteQuery()) => {
    let appId = routeQuery.app_id || routeQuery.appId
    // fixme
    if (!appId && isDebug()) {
      appId = '1258e3ea08af43cf882b3d07754dc2fd'
    }
    return appId
  }

  return {
    online: isOnline(),
    tag: matchRouteTag(routeQuery),
    appId: matchRouteAppId(routeQuery),
    userId: matchRouteUserId(routeQuery),
    refresh_intention: isRefreshIntention(routeQuery),
    use_faq_cache: !isRefreshFaqCache(routeQuery),
  }
}